<template>
    <!-- 卡片包裹表格，带有表头 -->
    <el-card style="max-width: 100%" shadow="hover">
        <template #header>
            <div class="card-header">
                <span>热点问题</span>
            </div>
        </template>
        <!-- 数据表格 -->
        <el-table :data="hotQuestions " style="width: 100%" :loading="loading">
            <slot>
                <el-table-column prop="context" label="问题" show-overflow-tooltip />
                <el-table-column prop="count" label="次数" show-overflow-tooltip sortable />
            </slot>
        </el-table>
    </el-card>
</template>

<script setup>
// 引入 Element Plus 组件
import { ElCard, ElTable, ElTableColumn } from 'element-plus'
// 引入 vue 响应式
import { ref, onMounted, onUnmounted } from 'vue'
import axios from 'axios'

// 表格数据
const hotQuestions  = ref([])
const loading = ref(false)

let timer = null

const fetchHotQuestions = async () => {
  loading.value = true
  try {
    const res = await axios.get('http://localhost:5231/api/SmartQA/popular-questions')
    // 适配后端结构
    let arr = res.data.popularQueries?.data || []
    hotQuestions.value = arr.map(item => ({
      context: item.query || '',
      count: item.count || 0
    }))
  } catch (e) {
    console.error('获取热点问题失败', e)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchHotQuestions()
  timer = setInterval(fetchHotQuestions, 30000) // 每30秒刷新一次
})

onUnmounted(() => {
  if (timer) clearInterval(timer)
})
</script>